package com.wangl.spring.service.chain;

import com.intellij.psi.*;
import com.wangl.spring.suggestion.SuggestionNodeTree;
import com.wangl.spring.suggestion.SuggestionNodeType;
import com.wangl.spring.utils.Annotations;
import com.wangl.spring.utils.PlaceholderResolver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

public class ValueAnnotationSuggestionTreeBuilder implements SuggestionTreeBuilder{
    @Override
    public void build(SuggestionNodeTree suggestionNodeTree, PsiClass psiClass) {
        PsiField[] allFields = psiClass.getAllFields();
        for (PsiField field : allFields) {
            build(suggestionNodeTree, field);
        }
    }

    @Override
    public void build(SuggestionNodeTree suggestionNodeTree, PsiMethod psiMethod) {

    }

    @Override
    public void build(SuggestionNodeTree suggestionNodeTree, PsiField field) {
        PsiAnnotation valueAnnotation = field.getAnnotation(Annotations.VALUE);
        if (valueAnnotation == null){
            return;
        }
        String value = getValue(valueAnnotation);
        List<String> placeholders = PlaceholderResolver.getPlaceholders(value);
        if (CollectionUtils.isEmpty(placeholders)){
            return;
        }
        for (String placeholder : placeholders) {
            suggestionNodeTree.insertNode(placeholder, field, SuggestionNodeType.ANNOTATION_VALUE);
        }
    }

    private String getValue(PsiAnnotation annotation){
        PsiAnnotationMemberValue value = annotation.findAttributeValue("value");
        if (value instanceof PsiLiteralExpression){
            return Objects.requireNonNull(((PsiLiteralExpression) value).getValue()).toString();
        }
        return "";
    }
}
